/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.garagesale.user.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.garagesale.data.Item;
import com.garagesale.data.User;
import com.garagesale.data.ShoppingCart;
import com.garagesale.data.DBAccess;
import com.garagesale.web.util.WebAction;
import java.util.Date;

/**
 *
 * @author Steven Wong
 */
public class AddItemToCartAction extends org.apache.struts.action.Action
{

    private static final String ForwardUrl = "itemAdded";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        int itemId = Integer.parseInt(request.getParameter("itemID"));

        String action = request.getParameter("action");

        Item item = DBAccess.getInstance().retrieveByID(Item.class, itemId);

        String sessionId = request.getSession().getId();
        User user = (User) request.getSession().getAttribute("user");
        Date date = new Date();


        // check if this item is getting removed from the cart
        if (WebAction.DELETE.isAction(action))
        {
            item.setShoppingCart(null);
            DBAccess.getInstance().update(item);

            request.getSession().setAttribute("cart", DBAccess.getInstance().retrieveByID(ShoppingCart.class, user.getShoppingCart().getShoppingCartId()));

            return mapping.findForward("itemRemoved");
        }

        // Check if the item belongs to a cart.
        if (null == item.getShoppingCart())
        {

            ShoppingCart cart =
                    DBAccess.getInstance().getShoppingCartByUserId(user.getUserID());

            if (cart == null)
            {
                // Create the shopping cart/
                cart = new ShoppingCart(
                        user,
                        sessionId,
                        date,
                        date,
                        null);

                int cartId = DBAccess.getInstance().create(cart);
                cart.setShoppingCartId(cartId);

                // update the item so that it is now in the cart
            }

            item.setShoppingCart(cart);


            DBAccess.getInstance().update(item);


            request.getSession().setAttribute("cart", DBAccess.getInstance().retrieveByID(ShoppingCart.class, cart.getShoppingCartId()));


        }
        return new ActionForward("/user/viewUser.do", true);
    }
}
